const { status, type } = require("express/lib/response");
const mongoose = require("mongoose");//建模前先进行数据库导入

//轮播图
const swiperSchema = new mongoose.Schema({
    imgUrl: {
        type: String,
        required: true,
    },
    link: {
        type: String,
    },
    createtime: {
        type: Date,
        default: Date.now  // 添加默认值
    }
});

//搭子订单
const orderSchema = new mongoose.Schema({
    // 系统生成字段
    order_id: { type: String, required: true, unique: true }, // 订单号(例: DD20240520123456)
    user_id: { type: String }, // 发起用户ID
    buddy_id: { type: String }, // 搭子ID
    buddy_name: { type: String }, // 搭子昵称
    buddy_phone: { type: String }, // 搭子手机号
    create_time: { type: Date, default: Date.now }, // 订单创建时间
    update_time: { type: Date, default: Date.now }, // 最后更新时间

    // 用户输入信息
    meet_info: {
        meet_time: { type: String, required: true }, // 约见时间
        meet_place: {
            name: { type: String, required: true }, // 地点名称
            address: { type: String, required: true }, // 详细地址
        },
        meet_Matters: { //约见事宜
            type: Array,
            default: []
        },
        contact: {
            name: { type: String, required: true }, // 姓名
            phone: { type: String, match: /^1[3-9]\d{9}$/ }, // 手机号(正则验证)
            wechat: { type: String } // 微信号(加密存储)
        }
    },

    // 业务逻辑字段
    status: {
        type: String,
        enum: ['pending', 'paid', 'confirmed', 'completed', 'canceled'],
        default: 'pending'
    }, // 订单状态
});

//关注和被关注类
const followSchema = new mongoose.Schema({
    // 关注者（主动发起关注的人）
    follower: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',  // 关联到用户模型
        required: true
    },
    // 被关注者（被关注的人）
    following: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',  // 关联到用户模型
        required: true
    },
    // 关注时间
    createdAt: {
        type: Date,
        default: Date.now
    }
});

// 创建复合唯一索引（防止重复关注）
followSchema.index({ follower: 1, following: 1 }, { unique: true });

const userSchema = new mongoose.Schema({
    SettledInfo: { //搭子用户类
        type: mongoose.Schema.Types.ObjectId,
        ref: 'SettledUser' // 关联到User模型
    },
    username: {
        type: String,//用户名
        unique: true,          // 确保用户名唯一
        default: () => {
            // 生成类似 "用户8348" 的随机用户名
            return `用户${Date.now()}${Math.floor(1000 + Math.random() * 9000)}`;
        },
        index: true // 显式创建索引
    },
    //用户登录类
    account: {
        type: String,
        required: true,//为空验证
        unique: true,
        match: [/^1(3[0-9]|4[0-9]|5[0-9]|7[0-9]|8[0-9])\d{8}$/, '手机号错误请重新输入'],//正则校验
    },
    password: {
        type: String,
        required: true,
        validate: {
            validator: function (v) {
                return /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/.test(v);
            },
            message: '密码需至少8位且包含字母和数字'
        }
    },
    //用户头像
    avatar: {
        type: String,
        default: 'http://ciyuanbanyou.cn/photos/avatar.jpg'
    },
    code: {
        type: String
    },
    //权限控制
    role: {
        type: String,
        enum: ['user', 'admin'],
        default: 'user'
    },
    userType: {
        type: Number,
        enum: [0, 1],
        default: 0
    },
    Creationtime: {
        type: Date,
        default: Date.now  // 添加默认值
    }
});

// 添加虚拟字段：我关注的人列表
userSchema.virtual('followingList', {
    ref: 'Follow',       // 关联关注模型
    localField: '_id',   // 当前模型的关联字段
    foreignField: 'follower', // 目标模型的关联字段
    justOne: false       // 获取多条记录
});

// 添加虚拟字段：我的粉丝列表
userSchema.virtual('followerList', {
    ref: 'Follow',
    localField: '_id',
    foreignField: 'following',
    justOne: false
});

// 启用虚拟字段的JSON转换
userSchema.set('toJSON', { virtuals: true });
userSchema.set('toObject', { virtuals: true });

//搭子模型
const Settled = new mongoose.Schema({
    userid: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User' // 关联到User模型
    },
    //用户头像
    avatar: {
        type: String,
        default: 'http://ciyuanbanyou.cn/photos/avatar.jpg',
    },
    address: {
        type: String,//地址
    },
    phone: { //手机号
        type: String,
        required: true,//为空验证
    },
    realName: {
        type: String,
        required: true,//为空验证
    },
    age: {
        type: Number,
        required: true,//必填 年龄18-50
        min: [18, '年龄不能小于18岁'],
        max: [30, '年龄不能超过30岁']
    },
    gender: {
        type: String,
        required: true,//性别
        enum: ['男', '女'],
        default: '未知'
    },
    idNumber: {
        type: String,
        required: true,//必填身份证号
    },
    idCardFront: {
        type: String,
        required: true,//身份证正面
    },
    idCardBack: {
        type: String,
        required: true,//身份证反面
    },
    lifePhotos: {
        type: Array,
        required: true,//生活照
        validate: {
            validator: v => v.length <= 6,
            message: '生活照不能超过6张'
        }
    },
    voiceUrl: {
        type: String,//语音URL
    },
    personalIntro: {
        type: String,
        required: true,//个人介绍
    },
    tag: { //兴趣爱好，标签
        type: Array,
        default: []
    },
    // 增强审核状态管理
    partnerAudit: {
        status: {
            type: String,
            enum: ['pending', 'approved', 'rejected'],//审核中 审核成功 审核失败
            default: 'pending'
        },
        applyAt: {
            type: Date,
            default: Date.now  // 申请时间
        },
        reviewedAt: {
            type: Date,
            default: Date.now  // 审核时间
        },
        reviewer: { type: mongoose.Schema.Types.ObjectId, ref: 'AdminSchema' }, // 审核人
        reviewNote: String    // 审核意见
    },
});

//用户tag兴趣标签
const tagsSchema = new mongoose.Schema({
    tag: {
        type: String,
        required: true,
    },
    url: {
        type: String,
        required: false,
    }
});

//用户动态模型
const dynamicsSchema = new mongoose.Schema({
    userid: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, // 动态所属用户
    createTime: {
        type: Date,
        default: Date.now  // 发布时间
    },
    title: {
        type: String,//文章标题
        required: true,
    },
    coverImage: {
        type: String,//封面图
    },
    describe: {
        type: String,//描述
        required: true,
    },
    links: {
        type: Array,//图片或者视频
        required: true,
    },
    tags: {
        type: Array,//话题标签
        required: true,
    },
    // 增强审核状态管理
    partnerAudit: {
        status: {
            type: String,
            enum: ['pending', 'approved', 'rejected'],//审核中 审核成功 审核失败
            default: 'pending'
        },
        applyAt: {
            type: Date,
            default: Date.now  // 申请时间
        },
        reviewedAt: {
            type: Date,
            default: Date.now  // 审核时间
        },
        reviewer: { type: mongoose.Schema.Types.ObjectId, ref: 'AdminSchema' }, // 审核人
        reviewNote: String    // 审核意见
    },
});

//话题动态标签tag
const topicTags = new mongoose.Schema({
    tag: {
        type: String,
        required: true,
    },
    url: {
        type: String,
        required: false,
    }
});

//创建模型
const User = mongoose.model('User', userSchema);
const SettledUser = mongoose.model('SettledUser', Settled);
const UserSwiper = mongoose.model('UserSwiper', swiperSchema);
const tags = mongoose.model('tags', tagsSchema);
const dynamics = mongoose.model('dynamics', dynamicsSchema);
const dynamicsTags = mongoose.model('topicTags', topicTags);
const OrdersSchema = mongoose.model('OrdersSchema', orderSchema);
const Follow = mongoose.model('Follow', followSchema);

//导出用户端数据模型
module.exports = { User, SettledUser, UserSwiper, tags, dynamics, dynamicsTags, OrdersSchema, Follow };